package net.sunbeta.test.util ;

import java.text.DecimalFormat ;

import org.apache.log4j.Logger ;

public class FormatUtils {

    private final static Logger LOG = Logger.getLogger(FormatUtils.class) ;

    public static String padLeftLong(long n, int padding) {

        return String.format("%0" + padding + "d", n) ;
    }

    public static String padDoubleLeft(Double d, int totalDigit, int fractionalDigit) {

        Double absValue = Math.abs(d) ;
        DecimalFormat decimalFormat = new DecimalFormat() ;
        decimalFormat.setMinimumFractionDigits(fractionalDigit) ;
        decimalFormat.setMaximumFractionDigits(fractionalDigit) ;
        decimalFormat.setGroupingUsed(false) ;
        decimalFormat.setMaximumIntegerDigits(totalDigit - fractionalDigit - 1) ;
        decimalFormat.setMinimumIntegerDigits(totalDigit - fractionalDigit - 1) ;

        return decimalFormat.format(absValue) ;
    }

    public static String padIntLeft(Double d, int totalDigit, int fractionalDigit) {

        String doublePad = padDoubleLeft(d, totalDigit, fractionalDigit) ;
        // .longValue 123.5568 should be 123
        Double newDouble = new Double(Double.valueOf(doublePad).longValue()) ;
        String intPad = padDoubleLeft(newDouble, totalDigit, fractionalDigit) ;
        return intPad ;
    }

    public static String padNaturalRoundedIntLeft(Double d, int totalDigit, int fractionalDigit) {

        String doublePad = padDoubleLeft(d, totalDigit, fractionalDigit) ;
        // Math.round 123.5568 should be 124
        Double newDouble = new Double(Math.round(Double.valueOf(doublePad))) ;
        String intPad = padDoubleLeft(newDouble, totalDigit, fractionalDigit) ;
        return intPad ;
    }

    // fill blank with ""
    public static String padStrLeft(String s, int totalDigit) {

        String padStr = s ;
        if (s == null || s.trim().length() == 0) {
            padStr = "" ;
        }

        padStr = padStr.trim() ;
        if (padStr.length() > totalDigit) {
            LOG.debug(String.format("the pad %s is more than size %d.", padStr, totalDigit)) ;
            padStr = padStr.substring(0, totalDigit) ;
        }

        return String.format("%1$-" + totalDigit + "s", padStr) ;
    }

    // fill blank with 0
    public static String padStrRight(String s, int totalDigit) {

        String padStr = s ;
        if (s == null || s.trim().length() == 0) {
            padStr = "" ;
        }

        padStr = padStr.trim() ;
        if (padStr.length() > totalDigit) {
            LOG.debug(String.format("the pad %s is more than size %d.", padStr, totalDigit)) ;
            padStr = padStr.substring(0, totalDigit) ;
        }

        String padedValue = String.format("%1$" + totalDigit + "s", padStr) ;
        return padedValue.replaceAll(" ", "0") ;
    }

}
